const fs = require('fs');
const path = require('path');
var child_process = require('child_process');
const { dir } = require('console');

var current = process.cwd(); // 当前路径

const projPath = current.split('image-tool')[0] + 'sesame-unity/sesame/';

/**
 * 裁剪红颜和门客的 道具icon
 * 需要在WSL里运行，需要ImageMagick
 */
function cropRoleIcon () {
  // 红颜全身像目录
  const fullDirPath = projPath + 'Assets/Game/Res/LuaAssets/image/wives/role/';
  // 红颜的icon背景图
  const boxPath =  projPath + 'Assets/Game/Res/LuaAssets/image/box/image_box_box167.png';
  // icon的生成目录
  const genDirPath =  projPath + 'Assets/Game/Res/Dynamic/Wife/icon/';
  // icon名称处理
  const replaceName = (name) => name.replace('wives_role', 'wife');
  const resize = '208x268';
  const crop = '114x116+47+34'

  // 门客全身像目录
  // const fullDirPath = current.replace('datacenter', 'Assets/Game/Res/Dynamic/Servant/half/');
  // // 门客的icon背景图
  // const boxPath = current.replace('datacenter', 'Assets/Game/Res/LuaAssets/image/box/image_box_box166.png')
  // // icon的生成目录
  // const genDirPath = current.replace('datacenter', 'Assets/Game/Res/Dynamic/Servant/icon/');
  // // icon名称处理
  // const replaceName = (name) => name.replace('servant_half', 'servant');
  // const resize = '134x156';
  // const crop = '114x116+10+13'


  if (!fs.existsSync(genDirPath)) {
    fs.mkdirSync(genDirPath, { recursive: true }); // recursive true表示没有父目录，也会创建父目录
  }
  // 将尺寸重置为150*194后， 再去裁剪， 按照（19，10）的偏移量裁剪出114*116尺寸图片
  child_process.execSync(`mogrify -path ${genDirPath} -resize ${resize} -crop ${crop} ${fullDirPath}/*.png`)

  const filePathes = fs.readdirSync(genDirPath);
  // 将icon背景图，调整尺寸到128 * 128
  const newBgPath = path.join(genDirPath, 'newBox.png');
  child_process.execSync(`convert ${boxPath} -resize 128x128 ${newBgPath}`)

  filePathes.forEach((x) => {
    if (!x.toLowerCase().endsWith('.png')) return; // 非图片
    const imgPath = path.join(genDirPath, x);
    // 开始合成
    child_process.execSync(`convert ${newBgPath} -gravity center -compose over ${imgPath} -composite ${imgPath}`)
    // 改名
    fs.renameSync(imgPath, replaceName(imgPath));
  })
  // 删除修改后的box
  // fs.rmSync(newBgPath)
}

/**
 * 检查皮肤资源
 */
function checkSkinAsset() {
  const rolePath = projPath + 'Assets/Game/Res/Dynamic/Skin/';
  const cdnPath = projPath + 'Assets/Game/Res/CDN/Partial/skin/';

  for (let i = 1; i <= 250; i++) {
    // 头像
    if (fs.existsSync(`${rolePath}head/skin_head_${i}.png`)) {
      if (!fs.existsSync(`${cdnPath}/${i}/`)) {
        fs.mkdirSync(`${cdnPath}/${i}/`)
      }
      // 移动
      if (!fs.existsSync(`${cdnPath}/${i}/head_${i}.png`)) {
        fs.renameSync(`${rolePath}head/skin_head_${i}.png`, `${cdnPath}/${i}/head_${i}.png`)
      } else {
        fs.rmSync(`${rolePath}head/skin_head_${i}.png`)
      }
    }
    // 全身像
    if (fs.existsSync(`${rolePath}full/skin_full_${i}.png`)) {
      if (!fs.existsSync(`${cdnPath}/${i}/`)) {
        fs.mkdirSync(`${cdnPath}/${i}/`)
      }
      // 移动
      if (!fs.existsSync(`${cdnPath}/${i}/full_${i}.png`)) {
        fs.renameSync(`${rolePath}full/skin_full_${i}.png`, `${cdnPath}/${i}/full_${i}.png`)
      } else { // 存在则删除包内资源
        fs.rmSync(`${rolePath}full/skin_full_${i}.png`)
      }
    }

    // 半裸
    if (fs.existsSync(`${rolePath}role_1/skin_role_1_${i}.png`)) {
      if (!fs.existsSync(`${cdnPath}/${i}/`)) {
        fs.mkdirSync(`${cdnPath}/${i}/`)
      }
      // 移动
      if (!fs.existsSync(`${cdnPath}/${i}/nocloth_${i}.png`)) {
        fs.renameSync(`${rolePath}role_1/skin_role_1_${i}.png`, `${cdnPath}/${i}/nocloth_${i}.png`)
      } else { // 存在则删除包内资源
        fs.rmSync(`${rolePath}role_1/skin_role_1_${i}.png`)
      }
    }

    const iconPath = `${projPath}Assets/Game/Res/LuaAssets/image/props/skinIcon/props_skinIcon_${i}.png`;
    // 道具图标
    if (fs.existsSync(iconPath)) {
      if (!fs.existsSync(`${cdnPath}/${i}/`)) {
        fs.mkdirSync(`${cdnPath}/${i}/`)
      }
      // 移动
      if (!fs.existsSync(`${cdnPath}/${i}/icon_${i}.png`)) {
        fs.renameSync(iconPath, `${cdnPath}/${i}/icon_${i}.png`)
      } else { // 存在则删除包内资源
        fs.rmSync(iconPath)
      }
    }
  }
}

// 校验名称是否 只包含 _.数字字母
function checkName(name) {
  let isErroName = false;
  for (let i = 0; i < name.length; i++) {
    const code = name[0].charCodeAt(0)
    if ((code >= '0'.charCodeAt(0) && code <= '9'.charCodeAt())
    || (name[0] === '_') || (name[0] === '.') 
    || (code >= 'A'.charCodeAt(0) && code <= 'Z'.charCodeAt(0))
    || (code >= 'a'.charCodeAt(0) && code <= 'z'.charCodeAt(0))) {
      continue;
    }
    isErroName = true;
    break;
  }
  if (isErroName) {
    console.log('错误的名字：', fullPath);
  }
}

function rename(parentPath, name, isFile) {
  // checkName(name);
  let newName = name;
  if (isFile) {
    newName = newName.replace('_cn', ''); // 把cn关键字去掉
  }

  newName = newName.replace(' ', ''); // 把空格去掉
  newName = newName.replace('TMPNew_', ''); // 把空格去掉
  const arr = [];
  let isNewName = name.length != newName.length;
  newName.split('_').forEach((sub) => {
    sub.split(' ').forEach((x) => {
      if (x[0] == null) return
      const code = x[0].charCodeAt(0);
      let newX = x;
      if (code <= 'z'.charCodeAt(0) && code >= 'a'.charCodeAt(0)) { // 小写字母
        const char = String.fromCharCode(code - 'a'.charCodeAt(0) + 'A'.charCodeAt(0));
        newX = char + x.substr(1);
        isNewName = true;
      }
      arr.push(newX);
    });
  });
  newName = arr.join('');
  if (isNewName) {
    if (name.indexOf('zh_hant') >= 0) return;
    if (name.indexOf('zh_hans') >= 0) return;
    /* 修改大小写
    if (name.length === newName.length) { // 说明只是切换了大小写
      newName = 'TMPNew_' + newName;
      console.log('newName:', parentPath, name, '=>', newName);
      if (!fs.existsSync(path.join(parentPath, name + '.meta'))) {
        console.error('meta不存在', parentPath, name + '.meta');
        return;
      }
      fs.renameSync(path.join(parentPath, name), path.join(parentPath, newName))
      fs.renameSync(path.join(parentPath, name + '.meta'), path.join(parentPath, newName + '.meta'))
    }
    else if (name.indexOf('TMPNew_') >= 0) {
      fs.renameSync(path.join(parentPath, name), path.join(parentPath, newName))
      fs.renameSync(path.join(parentPath, name + '.meta'), path.join(parentPath, newName + '.meta'))
      console.log(name, ' ===> ', newName);
    }
    */
    // 全部改
    // fs.renameSync(path.join(parentPath, name), path.join(parentPath, newName))
    // fs.renameSync(path.join(parentPath, name + '.meta'), path.join(parentPath, newName + '.meta'))
  }
}

function GetPathes(parentPath, dirPathes, filePathes) {
  const pathes = fs.readdirSync(parentPath);
  pathes.forEach((fileName) => {
    if (fileName.endsWith('.meta')) return;
    let isFile = fileName.indexOf('.') >= 0;
    const fullPath = path.join(parentPath, fileName)
    if (fullPath.indexOf('version.txt') >= 0) return;
    if (fullPath.indexOf('Resources') >= 0) return;
    // if (fullPath.indexOf('Res\\Font') >= 0) return;
    if (fileName.indexOf('VERSION_') >= 0) isFile = true;
    if (isFile) {
      filePathes.push(fullPath, fullPath);
    } else {
      // LuaAsset 和 CDN目录的文件暂不处理
      if (fullPath.indexOf('LuaAssets') >= 0) return;
      if (fullPath.indexOf('CDN') >= 0) return;
      dirPathes.push(path.join(fullPath));
      // fs.renameSync(path.join(fullPath), path.join(fullPath + 'TMP'))
      
      GetPathes(path.join(fullPath), dirPathes, filePathes);
    }
    rename(parentPath, fileName, isFile);
  });
}

function AdjustDirAndFileName() {
  const rootPath = projPath + 'Assets/Game/Res/Font';
  const dirPathes = [];
  const filePathes = [];
  GetPathes(rootPath, dirPathes, filePathes);
  console.log('目录数量：', dirPathes.length);
  // dirPathes.forEach((path) => console.log(path));
  console.log('文件数量：', filePathes.length);
  // filePathes.forEach((path) => console.log(path));
}

// AdjustDirAndFileName();

function AdjustCDNSKinSpint() {
  const rootPath = projPath + 'Assets/Game/Res/CDN/Partial/Skin';
  for (let index = 1; index < 250; index++) {
      const itemPath = path.join(rootPath, index.toString(), 'full_' + index);
      if (fs.existsSync(itemPath)) {
        console.log("------")
        // fs.renameSync(itemPath, path.join(rootPath, index.toString(), 'Spine'))
      }
  }
}

// AdjustCDNSKinSpint()

function Adjust(params) {
  
}
